package com.turing.draw.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.turing.draw.service.CorrectOCRAnalyzeJsonService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class CorrectOCRAnalyzeJsonServiceImpl implements CorrectOCRAnalyzeJsonService {

    private static final Log logger = LogFactory.getLog( CorrectOCRAnalyzeJsonServiceImpl.class );

    @Value( "${fdfs.domain}" )
    private String FDFS_FILE_DOMAIN;

    @Value( "${fdfs.base.path}" )
    private String BASE_PATH;


    @Autowired
    private FastFileStorageClient dfsClient;

    /*
     * ocr结果json文件中，部分行因为存在特殊字符，在输出的时候被替换了，
     * 所以给前端显示的时候需要补充为空白行，否则行号跟数量对不齐
     * */
    public  void doInterpolation( JSONArray array ) {
        for ( int j = 0; j < array.size(); j++ ) {
            JSONObject jsonObject = array.getJSONObject( j );

            String docID = jsonObject.getString( "docID" );
            String pageNo = jsonObject.getString( "pageNo" );

            jsonObject.remove( "contIndex" );

            JSONArray paragraphs = jsonObject.getJSONArray( "paragraphs" );

            JSONObject paraObj = paragraphs.getJSONObject( 0 );

            JSONArray lines = paraObj.getJSONArray( "lines" );

            JSONArray resLines = new JSONArray();

            //                        JSONObject lastObj = lines.getJSONObject( lines.size() );
            //                        Integer totalLineNo = lastObj.getInteger( "lineNo" );

            for ( int k = 0; k < lines.size(); k++ ) {

                JSONObject lineObj = lines.getJSONObject( k );
                Integer lineNo = lineObj.getInteger( "lineNo" );

                while ( resLines.size() < lineNo ) {
                    int size = resLines.size();
                    JSONObject emptyLine = new JSONObject();
                    emptyLine.put( "lineId", "line_" + pageNo + "_" + size + "_cusline" + size );
                    emptyLine.put( "lineNo", size );
                    emptyLine.put( "objContent", "" );

                    JSONArray emptyPos = new JSONArray();
                    emptyPos.add( 0 );
                    emptyPos.add( 0 );
                    emptyPos.add( 0 );
                    emptyPos.add( 0 );
                    emptyLine.put( "objPos", emptyPos );

                    emptyLine.put( "objType", "textLine" );

                    logger.info( ">>>>>>> adding empty line , page " + pageNo + ", before line " + lineNo + ", added line " + size );

                    resLines.add( emptyLine );
                }

                resLines.add( lineObj );
            }

            paraObj.put( "lines", resLines );
        }
    }

    public static JSONArray ConvertToJsonArray( String path ) {

        JSONArray jsonArray = null;
        BufferedReader reader = null;
        StringBuilder jsonStrs = new StringBuilder();
        InputStream inputStream = null;
        try {
            //绝对路径
            inputStream = new FileInputStream( path );

            InputStreamReader inputStreamReader = new InputStreamReader( inputStream, StandardCharsets.UTF_8);
            reader = new BufferedReader( inputStreamReader );
            String tempStr = null;
            while ( ( tempStr = reader.readLine() ) != null ) {
                jsonStrs.append( tempStr );
            }
            reader.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
            if ( reader != null ) {
                try {
                    reader.close();
                } catch ( IOException e ) {
                    e.printStackTrace();
                }
            }
            if ( inputStream != null ) {
                try {
                    inputStream.close();
                } catch ( IOException e ) {
                    e.printStackTrace();
                }
            }
        }
        try {
            jsonArray = JSONArray.parseArray( jsonStrs.toString().trim() );
        } catch ( IllegalStateException | JSONException ex ) {
            ex.printStackTrace();
        }
        return jsonArray;
    }

    public void populatePosInfo( JSONArray array ){
        int globalIndex = 0;
        Map<Integer, JSONObject> map = new HashMap<>();
        if(!CollectionUtils.isEmpty(array)){
            for (int i = 0; i < array.size(); i++) {
                JSONObject pageObj = array.getJSONObject( i );
                pageObj.put( "pageStartIndex",globalIndex );
                JSONArray paragraphs = pageObj.getJSONArray( "paragraphs" );
                if(!CollectionUtils.isEmpty(paragraphs)){
                    JSONObject linesObj = paragraphs.getJSONObject(0);
                    JSONArray lines = linesObj.getJSONArray( "lines" );
                    for (int j = 0; j < lines.size(); j++) {
                        JSONObject lineObj = lines.getJSONObject( j );
                        String objType = lineObj.getString("objType");
                        lineObj.put("lineStartIndex",globalIndex);
                        String objContent = lineObj.getString("objContent");
                        //注释原因：table类型删除了冒号，导致起始下标有问题，影响高亮 -fanyihang
//                        if(objType.equals("table")){
//                            objContent = objContent.replaceAll(":","");
//                        }
                        globalIndex += objContent.length();
                        lineObj.put("lineEndIndex",globalIndex);
                    }
                }
                pageObj.put( "pageEndIndex",globalIndex );
            }
        }
    }

    /*
     * 将pdf文件提交到fastDFS
     * */
    private String uploadFileToDFS( File file ) {
        try {
            FileInputStream fileInputStream = new FileInputStream( file );
            StorePath storePath = dfsClient.uploadFile( fileInputStream, fileInputStream.available(), "json", null );
            return storePath.getFullPath();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
        return "";
    }


}
